<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { recommendProductsUsingPost, searchProductsUsingPost } from '@/api/productController.ts'
import ImageList from '@/components/ImageList.vue'

const searchParams = ref<API.SearchProductDto>({
  current: 1,
  pageSize: 10,
})
const loading = ref(false)
const dataList = ref<API.ProductVo[]>([])
const total = ref<number>(0)

const doPageChange = (page: number, pageSize: number) => {
  searchParams.value.current = page
  searchParams.value.pageSize = pageSize
  loadData()
}

// 加载数据
const loadData = async () => {
  loading.value = true
  // 查询数据
  const res = await searchProductsUsingPost({
    ...searchParams.value,
  })
  if (res.code === 200 && res.data) {
    dataList.value = res.data.records
    total.value = res.data.total
  } else {
    message.error(res.message)
  }
  loading.value = false
}

// 搜索
const doSearch = () => {
  // 重置搜索条件
  searchParams.value.current = 1
  loadData()
}

// 商品推荐
const recommendProducts = async () => {
  const res = await recommendProductsUsingPost({
    count: 10,
  })
  if (res.code === 200 && res.data) {
    dataList.value = res.data as API.ProductVo[]
  } else {
    message.error(res.message)
  }
}

onMounted(() => recommendProducts())
</script>

<template>
  <div id="home-view">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <a-input-search
        v-model:value="searchParams.name"
        placeholder="从海量商品中搜索"
        enter-button="搜索"
        size="large"
        @search="doSearch"
      />
    </div>
    <!-- 图片列表 -->
    <image-list :data-list="dataList" :loading="loading" />
    <a-pagination
      style="text-align: right"
      v-model:current="searchParams.current"
      v-model:page-size="searchParams.pageSize"
      :total="total"
      @change="doPageChange"
    />
  </div>
</template>

<style scoped>
#home-view .search-bar {
  max-width: 480px;
  margin: 0 auto 16px;
}
</style>
